<?php

/**
 * 通用类 curl 中转接口
 */
require_once __DIR__ . '/inc/config.inc.php';

$json = file_get_contents("php://input");
//error_log($json,3,"json.log");
$res = json_decode($json, true);

$method     = $res['method'];                                   //请求方式
$url        = $res['url'];                                      //请求URI
$data       = isset($res['data']) ? $res['data'] : [];          //请求data JOSN字符串
$headers    = isset($res['headers']) ? $res['headers'] : [];    //请求header JOSN字符串


if (!$method) {
    ApiBack::error('method不能为空');
}
if (!$url) {
    ApiBack::error('url不能为空');
}

$method = strtoupper($method);


$ci = curl_init();

// curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

//header
if($headers) {
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
}

curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE);

//设置浏览器
curl_setopt($ci, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ci, CURLOPT_HEADER, FALSE);

switch ($method) {
    case 'POST':
        //发送一个常规的Post请求
        curl_setopt($ci, CURLOPT_POST, TRUE);
        curl_setopt($ci,  CURLOPT_POSTFIELDS, $data);

        break;
    case 'GET':
        curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'GET');
        //分析网址中的参数
        if(!empty($data)){
            $paramUrl = http_build_query($data, '', '&');
            $extStr   = (strpos($url, '?') !== false) ? '&' : '?';
            $url      = $url . (($paramUrl) ? $extStr . $paramUrl : '');
        }
        
        break;
    case 'DELETE':
        curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
        //分析网址中的参数
        if(!empty($data)){
            $paramUrl = http_build_query($data, '', '&');
            $extStr   = (strpos($url, '?') !== false) ? '&' : '?';
            $url      = $url . (($paramUrl) ? $extStr . $paramUrl : '');
        }
}
curl_setopt($ci, CURLOPT_URL, $url);

//使用自动跳转
//curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ci, CURLOPT_TIMEOUT, 30);

$response = curl_exec($ci);

if(curl_errno($ci)){
    $err = curl_error($ci);
    curl_close($ci);
    ApiBack::error($err);
}

curl_close($ci);

ApiBack::success($response);
